<template>
  <div style="padding: 10px; margin-bottom: 50px">
    <el-row>
      <el-col :span="8">
        <!-- 辅导员列表 -->
        <el-card
          v-if="identity === 'stu'"
          style="width: 100%; min-height: 300px; color: #333"
        >
          <div style="padding-bottom: 10px; border-bottom: 1px solid #ccc">
            辅导员<span style="font-size: 12px">（点击聊天气泡开始聊天）</span>
          </div>
          <div style="padding: 10px 0">
            <el-avatar
              :size="50"
              :src="'data:image/jpeg;base64,' + usertea.img"
              style="margin-right: 10px"
            />
            <span>{{ usertea.name }}</span>
            <i
              class="el-icon-chat-dot-round"
              style="margin-left: 10px; font-size: 16px; cursor: pointer"
              @click="
                (chatUser = usertea.username),
                  (chatUserAvatar = usertea.avatar),
                  (chatUserAvatardata = usertea.img);
                loadMessages();
                updateread(usertea.username, this.user.username);
              "
            >
              <el-icon><iphone /></el-icon>
            </i>
            <span
              v-if="usertea.count > 0"
              style="color: red; margin-left: 8px; font-size: 12px"
            >
              （未读{{ usertea.count }}条）
            </span>

            <span
              v-if="usertea.username === chatUser"
              style="font-size: 12px; color: limegreen; margin-left: 5px"
            >
              chatting...
            </span>
          </div>
        </el-card>
        <!-- 宿舍管理员列表 -->
        <el-card
          v-if="identity === 'stu'"
          style="width: 100%; min-height: 300px; color: #333"
        >
          <div style="padding-bottom: 10px; border-bottom: 1px solid #ccc">
            宿舍管理员<span style="font-size: 12px"
              >（点击聊天气泡开始聊天）</span
            >
          </div>
          <div v-for="user in userdor" :key="user.name" style="padding: 10px 0">
            <el-avatar
              :size="50"
              :src="'data:image/jpeg;base64,' + user.img"
              style="margin-right: 10px"
            />
            <span>{{ user.name }}</span>
            <i
              class="el-icon-chat-dot-round"
              style="margin-left: 10px; font-size: 16px; cursor: pointer"
              @click="
                (chatUser = user.username),
                  (chatUserAvatar = user.avatar),
                  (chatUserAvatardata = user.img);
                loadMessages();
                updateread(user.username, this.user.username);
              "
            >
              <el-icon><iphone /></el-icon>
            </i>
            <span
              v-if="user.count > 0"
              style="color: red; margin-left: 8px; font-size: 12px"
            >
              （未读{{ user.count }}条）
            </span>
            <span
              v-if="user.username === chatUser"
              style="font-size: 12px; color: limegreen; margin-left: 5px"
            >
              chatting...
            </span>
          </div>
        </el-card>

        <!-- 宿舍管理员列表 -->
        <el-card
          v-if="identity === 'teacher'"
          style="width: 100%; height: 300px; color: #333; overflow: hidden"
        >
          <div style="padding-bottom: 10px; border-bottom: 1px solid #ccc">
            宿舍管理员
            <span style="font-size: 12px">（点击聊天气泡开始聊天）</span>
          </div>

          <!-- 滚动区域容器 -->
          <div style="height: 240px; overflow-y: auto; padding-right: 5px">
            <div
              v-for="user in useralldor"
              :key="user.dormManager.name"
              style="padding: 10px 0; display: flex; align-items: center"
            >
              <el-avatar
                :size="50"
                :src="'data:image/jpeg;base64,' + user.img"
                style="margin-right: 10px"
              />
              <span>{{ user.dormManager.name }}</span>
              <i
                class="el-icon-chat-dot-round"
                style="margin-left: 10px; font-size: 16px; cursor: pointer"
                @click="
                  (chatUser = user.dormManager.username),
                    (chatUserAvatar = user.dormManager.avatar),
                    (chatUserAvatardata = user.img);
                  loadMessages();
                  updateread(user.dormManager.username, this.user.username);
                "
              >
                <el-icon><iphone /></el-icon>
              </i>
              <span
                v-if="user.count > 0"
                style="color: red; margin-left: 8px; font-size: 12px"
              >
                （未读{{ user.count }}条）
              </span>
              <span
                v-if="user.dormManager.username === chatUser"
                style="font-size: 12px; color: limegreen; margin-left: 5px"
              >
                chatting...
              </span>
            </div>
          </div>
        </el-card>

        <!-- 学生列表 -->
        <!-- 学生列表 -->
        <el-card
          v-if="identity === 'teacher'"
          style="width: 100%; height: 300px; color: #333; overflow: hidden"
        >
          <div style="padding-bottom: 10px; border-bottom: 1px solid #ccc">
            学生
            <span style="font-size: 12px">（点击聊天气泡开始聊天）</span>
          </div>

          <!-- 滚动区域容器 -->
          <div style="height: 240px; overflow-y: auto; padding-right: 5px">
            <div
              v-for="user in userstu"
              :key="user.name"
              style="padding: 10px 0; display: flex; align-items: center"
            >
              <el-avatar
                :size="50"
                :src="'data:image/jpeg;base64,' + user.img"
                style="margin-right: 10px"
              />
              <span>{{ user.name }}</span>
              <i
                class="el-icon-chat-dot-round"
                style="margin-left: 10px; font-size: 16px; cursor: pointer"
                @click="
                  (chatUser = user.username),
                    (chatUserAvatar = user.avatar),
                    (chatUserAvatardata = user.img);
                  loadMessages();
                  updateread(user.username, this.user.username);
                "
              >
                <el-icon><iphone /></el-icon>
              </i>
              <span
                v-if="user.count > 0"
                style="color: red; margin-left: 8px; font-size: 12px"
              >
                （未读{{ user.count }}条）
              </span>
              <span
                v-if="user.username === chatUser"
                style="font-size: 12px; color: limegreen; margin-left: 5px"
              >
                chatting...
              </span>
            </div>
          </div>
        </el-card>

        <!-- 所有老师管理员列表 -->
        <el-card
          v-if="identity === 'dormManager'"
          style="width: 100%; height: 300px; color: #333; overflow: hidden"
        >
          <div style="padding-bottom: 10px; border-bottom: 1px solid #ccc">
            辅导员
            <span style="font-size: 12px">（点击聊天气泡开始聊天）</span>
          </div>

          <!-- 滚动区域容器 -->
          <div style="height: 240px; overflow-y: auto; padding-right: 5px">
            <div
              v-for="user in useralltea"
              :key="user.teacher.name"
              style="padding: 10px 0; display: flex; align-items: center"
            >
              <el-avatar
                :size="50"
                :src="'data:image/jpeg;base64,' + user.img"
                style="margin-right: 10px"
              />
              <span>{{ user.teacher.name }}</span>
              <i
                class="el-icon-chat-dot-round"
                style="margin-left: 10px; font-size: 16px; cursor: pointer"
                @click="
                  (chatUser = user.teacher.username),
                    (chatUserAvatar = user.teacher.avatar),
                    (chatUserAvatardata = user.img);
                  loadMessages();
                  updateread(user.teacher.username, this.user.username);
                "
              >
                <el-icon><iphone /></el-icon>
              </i>
              <span
                v-if="user.count > 0"
                style="color: red; margin-left: 8px; font-size: 12px"
              >
                （未读{{ user.count }}条）
              </span>
              <span
                v-if="user.teacher.username === chatUser"
                style="font-size: 12px; color: limegreen; margin-left: 5px"
              >
                chatting...
              </span>
            </div>
          </div>
        </el-card>

        <!-- 学生列表 -->
        <!-- 学生列表 -->
        <el-card
          v-if="identity === 'dormManager'"
          style="width: 100%; height: 300px; color: #333; overflow: hidden"
        >
          <div style="padding-bottom: 10px; border-bottom: 1px solid #ccc">
            学生
            <span style="font-size: 12px">（点击聊天气泡开始聊天）</span>
          </div>

          <!-- 滚动区域容器 -->
          <div style="height: 240px; overflow-y: auto; padding-right: 5px">
            <div
              v-for="user in userallstu"
              :key="user.student.name"
              style="padding: 10px 0; display: flex; align-items: center"
            >
              <el-avatar
                :size="50"
                :src="'data:image/jpeg;base64,' + user.img"
                style="margin-right: 10px"
              />
              <span>{{ user.student.name }}</span>
              <i
                class="el-icon-chat-dot-round"
                style="margin-left: 10px; font-size: 16px; cursor: pointer"
                @click="
                  (chatUser = user.student.username),
                    (chatUserAvatar = user.student.avatar),
                    (chatUserAvatardata = user.img);
                  loadMessages();
                  updateread(user.student.username, this.user.username);
                "
              >
                <el-icon><iphone /></el-icon>
              </i>
              <span
                v-if="user.count > 0"
                style="color: red; margin-left: 8px; font-size: 12px"
              >
                （未读{{ user.count }}条）
              </span>
              <span
                v-if="user.student.username === chatUser"
                style="font-size: 12px; color: limegreen; margin-left: 5px"
              >
                chatting...
              </span>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="16">
        <div
          style="
            width: 800px;
            margin: 0 auto;
            background-color: white;
            border-radius: 5px;
            box-shadow: 0 0 10px #ccc;
          "
        >
          <div style="text-align: center; line-height: 50px">聊天室</div>
          <div
            style="height: 350px; overflow: auto; border-top: 1px solid #ccc"
            v-html="content"
            ref="chatContent"
          ></div>
          <div style="height: 200px">
            <textarea
              v-model="text"
              style="
                height: 160px;
                width: 100%;
                padding: 20px;
                border: none;
                border-top: 1px solid #ccc;
                border-bottom: 1px solid #ccc;
                outline: none;
              "
            ></textarea>
            <div style="text-align: right; padding-right: 10px">
              <el-button type="primary" size="mini" @click="send"
                >发送</el-button
              >
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import request from "@/utils/request";

import { ChatDotRound } from "@element-plus/icons-vue";
import { fr } from "element-plus/es/locale/index.mjs";
let socket;
export default {
  components: {
    ChatDotRound,
  },
  name: "Im",
  data() {
    return {
      circleUrl:
        "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png",
      user: {},
      isCollapse: false,
      users: [],
      chatUser: "",
      chatUserAvatar: "",
      chatUserAvatardata: "",
      text: "",
      messages: [],
      content: "",
      tableData: [],
      pageSize: 50,
      usertea: {},
      userdor: [],
      userstu: [],
      useralldor: [],
      useralltea: [],
      userallstu: [],
      identity: "",
      img: "",
      unreadCount: 11,
    };
  },
  created() {
    this.identity = JSON.parse(sessionStorage.getItem("identity"));
    this.myAvatar();
    this.findTeacher();
    this.findDorm();
    this.findAllDorm();
    this.findStudent();
    this.findAllTea();
    this.findAllStu();
    this.init();
  },

  methods: {
    async myAvatar() {
      this.user = JSON.parse(sessionStorage.getItem("user"));
      this.img = await this.getAvatar(this.user.avatar);
    },

    // 获取头像方法（修正版）
    async getAvatar(filename) {
      try {
        const res = await request.get(`/files/initAvatar/${filename}`);
        return res.data.data; // 假设返回结构是 { data: base64编码 }
      } catch (error) {
        console.error("获取头像失败:", error);
        return "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png"; // 默认头像
      }
    },
    async findTeacher() {
      let teauser = JSON.parse(sessionStorage.getItem("user"));
      try {
        const res = await request.get(
          "/teacher/classname/" + teauser.classname
        );
        console.log("res", res);
        this.usertea = res.data;

        // 获取头像，等待 base64 数据回来
        if (this.usertea && this.usertea.avatar) {
          this.usertea.img = await this.getAvatar(this.usertea.avatar);
        }
        console.log("tea", this.usertea);
        this.usertea.count = await this.getUnreadCount(
          this.user.username,
          this.usertea.username
        );

        console.log("tea", this.usertea);
        this.loading = false;
      } catch (error) {
        console.error("加载教师信息失败:", error);
        this.loading = false;
      }
    },

    async findAllDorm() {
      try {
        const res = await request.get("/dormManager/findList", {
          params: {
            pageNum: 1,
            pageSize: 100,
            search: "",
          },
        });
        this.useralldor = res.data.records;

        // 使用 Promise.all 来并行加载头像和未读消息数
        await Promise.all(
          this.useralldor.map(async (user) => {
            user.img = await this.getAvatar(user.dormManager.avatar);
            user.count = await this.getUnreadCount(
              this.user.username,
              user.username
            );
          })
        );

        this.loading = false;
      } catch (error) {
        console.error("加载宿管信息失败all:", error);
        this.loading = false;
      }
    },
    async findAllTea() {
      try {
        const res = await request.get("/teacher/findList", {
          params: {
            pageNum: 1,
            pageSize: 100,
            search: "",
          },
        });
        this.useralltea = res.data.records;

        // 使用 Promise.all 来并行加载头像和未读消息数
        await Promise.all(
          this.useralltea.map(async (user) => {
            user.img = await this.getAvatar(user.teacher.avatar);
            user.count = await this.getUnreadCount(
              this.user.username,
              user.username
            );
          })
        );

        this.loading = false;
      } catch (error) {
        this.loading = false;
      }
    },

    async findAllStu() {
      try {
        const res = await request.get("/stu/findList", {
          params: {
            pageNum: 1,
            pageSize: 100,
            search: "",
          },
        });
        this.userallstu = res.data.records;

        // 使用 Promise.all 来并行加载头像和未读消息数
        await Promise.all(
          this.userallstu.map(async (user) => {
            user.img = await this.getAvatar(user.student.avatar);
            user.count = await this.getUnreadCount(
              this.user.username,
              user.username
            );
          })
        );

        this.loading = false;
      } catch (error) {
        this.loading = false;
      }
    },

    async findDorm() {
      let doruser = JSON.parse(sessionStorage.getItem("user"));
      try {
        const res = await request.get(
          "/dormManager/getdorm/" + doruser.username
        );
        this.userdor = res.data;

        // 使用 Promise.all 来并行加载头像和未读消息数
        await Promise.all(
          this.userdor.map(async (user) => {
            user.img = await this.getAvatar(user.avatar);
            user.count = await this.getUnreadCount(
              this.user.username,
              user.username
            );
          })
        );

        console.log("dor", this.userdor);
        this.loading = false;
      } catch (error) {
        console.error("加载宿管信息失败:", error);
        this.loading = false;
      }
    },
    async findStudent() {
      let stuuser = JSON.parse(sessionStorage.getItem("user"));
      try {
        const res = await request.get("/stu/classname/" + stuuser.classname);
        this.userstu = res.data;

        // 使用 Promise.all 来并行加载头像和未读消息数
        await Promise.all(
          this.userstu.map(async (user) => {
            user.img = await this.getAvatar(user.avatar);
            user.count = await this.getUnreadCount(
              this.user.username,
              user.username
            );
          })
        );

        console.log("stu", this.userstu);
        this.loading = false;
      } catch (error) {
        console.error("加载学生信息失败:", error);
        this.loading = false;
      }
    },
    load() {
      request
        .get("imsingle?fromUser" + this.fromUser + "toUser=" + this.toUser)
        .then((res) => {
          if (res.code === "0") {
            this.messages = res.data;
            this.scrollToBottom(); //
          } else {
            this.$notify.error(res.msg);
          }
          this.loadUnReadNuns();
        });
    },

    send() {
      if (!this.chatUser) {
        this.$message({ type: "warning", message: "请选择聊天对象" });
        return;
      }
      if (!this.text) {
        this.$message({ type: "warning", message: "请输入内容" });
      } else {
        if (typeof WebSocket == "undefined") {
          console.log("您的浏览器不支持WebSocket");
        } else {
          console.log("您的浏览器支持WebSocket");
          // 组装待发送的消息 json
          // {"from": "zhang", "to": "admin", "text": "聊天文本"}
          let message = {
            from: this.user.username,
            fromavatar: this.user.avatar,
            to: this.chatUser,
            toavatar: this.chatUserAvatar,
            text: this.text,
          };
          socket.send(JSON.stringify(message)); // 将组装好的json发送给服务端，由服务端进行转发
          this.messages.push({ user: this.user.username, text: this.text });
          // 构建消息内容，本人消息
          this.createContent(null, this.user.username, this.text);
          this.text = "";
        }
      }
    },
    // 获取未读消息数
    async getUnreadCount(tousername, fromusername) {
      try {
        const res = await request.get("/imsingle/unread/count", {
          params: {
            fromUser: fromusername, // 辅导员
            toUser: tousername, // 当前登录学生
          },
        });
        console.log("tousername", tousername);
        console.log("fromusername", fromusername);
        return res.data; // 记录条数
      } catch (e) {
        console.error("获取未读消息失败", e);
      }
    },
    // 已读
    async updateread(from, to) {
      try {
        await request.put(`/imsingle/update/${from}/${to}`);
      } catch (e) {
        console.error("更新已读状态失败", e);
      }
    },
    // 加载聊天记录
    async loadMessages() {
      if (!this.chatUser || !this.user.username) return;
      try {
        const res = await request.get("/imsingle/history", {
          params: {
            fromUser: this.user.username,
            toUser: this.chatUser,
          },
        });
        console.log("-----------------------------", res);

        this.messages = res.data || [];
        // 成功加载后渲染
        this.renderMessages();
        //
      } catch (e) {
        console.error("加载聊天记录失败", e);
      }
    },
    renderMessages() {
      this.content = "";

      this.messages.forEach((msg) => {
        const nowUser = msg.fromuser === this.user.username; // 当前用户发的消息
        const remoteUser = msg.fromuser === this.chatUser; // 远程用户发的消息

        this.createContent(remoteUser, nowUser, msg.content, msg.time);
      });
      // 自动滚动到底部
      this.$nextTick(() => {
        const container = this.$refs.chatContent;
        if (container) container.scrollTop = container.scrollHeight;
      });
    },

    createContent(remoteUser, nowUser, text, rawTime) {
      // 时间格式化函数：将 ISO 时间字符串转为 YYYY-MM-DD HH:mm 格式
      const formatTime = (isoString) => {
        const date = new Date(isoString);
        const year = date.getFullYear();
        const month = (date.getMonth() + 1).toString().padStart(2, "0");
        const day = date.getDate().toString().padStart(2, "0");
        const hour = date.getHours().toString().padStart(2, "0");
        const minute = date.getMinutes().toString().padStart(2, "0");
        return `${year}-${month}-${day} ${hour}:${minute}`;
      };

      const showTime = rawTime
        ? formatTime(rawTime)
        : new Date().toLocaleString();
      let html;

      if (nowUser) {
        // 当前用户发送
        html = `
    <div style="text-align: center; margin: 10px 0; color: #999; font-size: 12px;">
      ${showTime}
    </div>
    <div class="el-row" style="padding: 5px 0">
      <div class="el-col el-col-22" style="text-align: right; padding-right: 10px">
        <div class="tip left">${text}</div>
      </div>
      <div class="el-col el-col-2">
        <span class="el-avatar el-avatar--circle" style="height: 40px; width: 40px; line-height: 40px;">
          <img src="data:image/jpeg;base64,${this.img}" style="object-fit: cover;">
        </span>
      </div>
    </div>`;
      } else if (remoteUser) {
        // 远程用户发送
        html = `
    <div style="text-align: center; margin: 10px 0; color: #999; font-size: 12px;">
      ${showTime}
    </div>
    <div class="el-row" style="padding: 5px 0">
      <div class="el-col el-col-2" style="text-align: right">
        <span class="el-avatar el-avatar--circle" style="height: 40px; width: 40px; line-height: 40px;">
          <img src="data:image/jpeg;base64,${this.chatUserAvatardata}" style="object-fit: cover;">
        </span>
      </div>
      <div class="el-col el-col-22" style="text-align: left; padding-left: 10px">
        <div class="tip right">${text}</div>
      </div>
    </div>`;
      }

      console.log(html);
      this.content += html;
    },

    init() {
      this.user = sessionStorage.getItem("user")
        ? JSON.parse(sessionStorage.getItem("user"))
        : {};
      let username = this.user.username;
      let _this = this;
      if (typeof WebSocket == "undefined") {
        console.log("您的浏览器不支持WebSocket");
      } else {
        console.log("您的浏览器支持WebSocket");
        let socketUrl = "ws://localhost:9092/imserver/" + username;
        if (socket != null) {
          socket.close();
          socket = null;
        }
        // 开启一个websocket服务
        socket = new WebSocket(socketUrl);
        //打开事件
        socket.onopen = function () {
          console.log("websocket已打开");
        };
        //  浏览器端收消息，获得从服务端发送过来的文本消息
        socket.onmessage = function (msg) {
          console.log("收到数据====" + msg.data);
          let data = JSON.parse(msg.data); // 对收到的json数据进行解析， 类似这样的： {"users": [{"username": "zhang"},{ "username": "admin"}]}
          if (data.users) {
            // 获取在线人员信息
            _this.users = data.users.filter(
              (user) => user.username !== username
            ); // 获取当前连接的所有用户信息，并且排除自身，自己不会出现在自己的聊天列表里
          } else {
            // 如果服务器端发送过来的json数据 不包含 users 这个key，那么发送过来的就是聊天文本json数据
            //  // {"from": "zhang", "text": "hello"}
            if (data.from === _this.chatUser) {
              _this.messages.push(data);
              // 构建消息内容
              _this.createContent(data.from, null, data.text);
            }
          }
        };
        //关闭事件
        socket.onclose = function () {
          console.log("websocket已关闭");
        };
        //发生了错误事件
        socket.onerror = function () {
          console.log("websocket发生了错误");
        };
      }
    },
  },
};
</script>
<style>
.tip {
  color: white;
  text-align: center;
  border-radius: 10px;
  font-family: sans-serif;
  padding: 10px;
  width: auto;
  display: inline-block !important;
  display: inline;
}
.right {
  background-color: deepskyblue;
}
.left {
  background-color: forestgreen;
}
</style>
